const sharp = require('sharp')
const R = require('ramda')
var rewire = require("rewire")
const {asyncMap} = rewire('./combinator.cjs')
const {getVal, uuid, splitArray2} = rewire('./utils.cjs')
const {deleteFile} = rewire('./file.cjs')

async function cutPic(savePath, path, point, width, heigth) {
    await sharp(path)
	.extract({ width, height, left: point.x, top: point.y })
	.toFile(savePath)
    return savePath
}


// 忽略像素上限
const limitInputPixels = false

function emptyImage(width, height) {
    return sharp({
	create: {
	    background: "#ffffff",
	    channels: 4,
	    width: width,
	    height: height,
	},
	limitInputPixels,
    })
}

// direc=1垂直拼接 direc=2水平拼接
async function splicePics(savePath, direc, ...pics) {
    if (R.length(pics) > 50) {
	const pies = splitArray2(pics, 2)
	const tmp1 = `./${uuid()}.png`
	const tmp2 = `./${uuid()}.png`
	await splicePics(tmp1, direc, ...pies[0])
	await splicePics(tmp2, direc, ...pies[1])
	await splicePics(savePath, direc, tmp1, tmp2)
	deleteFile(tmp1)
	deleteFile(tmp2)
	return
    }
    
    const metas = await asyncMap(async function(p) { return await sharp(p, {limitInputPixels}).metadata() }, pics)
    const getHeight = R.partialRight(getVal, ['height'])
    const getWidth = R.partialRight(getVal, ['width'])
    // 如果是垂直
    if (direc == 1) {
	const height = R.reduce(R.add, 0, R.map(getHeight, metas))
	const width = R.max(0, ...R.map(getWidth, metas))
	const fileObjList = R.values(R.mapObjIndexed(function(pic, i) {
	    return {
		input: pic,
		top: R.reduce(R.add, 0, R.map(getHeight, R.take(i, metas))),
		left: 0,
		limitInputPixels
	    }
	}, pics))

	await emptyImage(width, height).composite(fileObjList).png().toFile(savePath)
    }
    // 如果是水平
    else {
	const height = R.max(0, ...R.map(getHeight, metas))
	const width = R.reduce(R.add, 0, R.map(getWidth, metas))
	const fileObjList = R.values(R.mapObjIndexed(function(pic, i) {
	    return {
		input: pic,
		top: 0,
		left: R.reduce(R.add, 0, R.map(getWidth, R.take(i, metas))),
		limitInputPixels
	    }
	}, pics))

	await emptyImage(width, height).composite(fileObjList).png().toFile(savePath)
    }
}
// splicePics('e:/media/aat.png', 2, 'e:/media/map/3210_1904.png', 'e:/media/map/3210_1905.png', 'e:/media/map/3210_1906.png')

module.exports = {cutPic, splicePics}
//cutPic('e:/mumu1.png', 'e:/MuMu20211117112738.png', {x: 150, y: 65}, 100, 25)
